package com.rslai.commons.validator.jsonvalidator.validators;

import org.junit.Assert;

import java.util.ArrayList;
import java.util.List;

import static com.rslai.commons.validator.jsonvalidator.matchers.Allowed.allowed;

/**
 * JSON校验器，Allowed校验器
 */
public class AllowedValidator extends Validator {
    public static final String VALIDATOR_NAME = "allowed";
    private List<Object> allowedList = new ArrayList<Object>();

    /**
     * 构造函数
     * @param alloweds alloweds
     */
    public AllowedValidator(List<Object> alloweds) {
        allowedList.clear();
        if (alloweds != null) {
            this.allowedList.addAll(alloweds);
        }
    }

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    @Override
    public void doValidate(Object object) {
        if (object instanceof List) {
            for (Object o : (List) object) {
                Assert.assertThat(getCurrentKeyPath(), o, allowed(allowedList));
            }
        }
        if (object != null && object.getClass().isArray()) {
            for (Object o : (Object[]) object) {
                Assert.assertThat(getCurrentKeyPath(), o, allowed(allowedList));
            }
        }
        Assert.assertThat(getCurrentKeyPath(), object, allowed(allowedList));
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }
}
